<?php
/**
 * 销量信息（促销员考核）模块
 */
class salesAction extends apiAction {
	
	/**
	 * 销量录入
	 */
	public function add(){
		
		$data['imei'] = I('imei');
		$data['modelId'] = I('modelId');
		$data['userId'] = $this->user['id'];
		$data['storeId'] = $this->user['storeId'];
		$data['createTime'] = time();
		
		$module = D(MODULE_NAME);
		if (!$module->create($data)){
			$this->ajaxReturn(300, $module->getError());
		}
		
		if(! $data['modelId']){
			$this->ajaxReturn(300, '机型信息有误！');
		}
		
		if($module->add($data)){
			// 减库存
			D('inventory')->where(array('storeId'=>$data['storeId'],'modelId'=>$data['modelId']))->save(array('salesInventory'=>array('exp','salesInventory-1')));
			$this->ajaxReturn(200, L('success'));
		}else{
			$this->ajaxReturn(300, L('error'));
		}
	}
	
	/**
	 * 我的销量
	 */
	public function my(){
		$list = array();
		$startTime = strtotime("-1 month"); //  取上个月和本月的销量
		$sales = D(MODULE_NAME)->field("COUNT(*) AS count, DATE_FORMAT(FROM_UNIXTIME(createTime),'%Y-%m') AS m, DATE_FORMAT(FROM_UNIXTIME(createTime),'%Y-%m-%d') AS day")->where("userId={$this->user['id']} AND createTime>={$startTime}")
				->group("DATE_FORMAT(FROM_UNIXTIME(createTime),'%Y-%m-%d')")->select();
		
		foreach ($sales as $row){
			$list[$row['m']]['month'] = $row['m'];
			$list[$row['m']]['total'] += $row['count'];
			$list[$row['m']]['days'][] = $row;
		}
		rsort($list);
	
		$this->assign('list',$list);
		$this->display();
	}
	
	/**
	 * 我的销量列表详情
	 */
	public function myList(){
		$day = I('day');
		$sales = D(MODULE_NAME)->alias("s")->field("s.*, m.name AS model, b.name AS brand, c.status AS checkType, c.saledate, c.provid")
				->join(C('DB_PREFIX')."model AS m ON m.id = s.modelId")
				->join(C('DB_PREFIX')."brand AS b ON b.id = m.brandId")
				->join(C('DB_PREFIX')."sales_imeicheck AS c ON c.imei = s.imei")
				->where("s.userId={$this->user['id']} AND DATE_FORMAT(FROM_UNIXTIME(s.createTime),'%Y-%m-%d') ='{$day}'")
				->select();
		
		$list['day'] = $day;
		$list['count'] = count($sales);
		$list['sales'] = $sales;

		//$this->assign('ctms', C('IMEI_CHECK_TYPE'));
		$this->assign('list',$list);
		$this->display();
	}
	
	/**
	 * 销量查询
	 */
	public function search(){
		$storeId	= I('storeId');		//营业厅id
		$microAreaId= I('microAreaId');	//片区id
		$cityId		= I('cityId');		//城市id
		
		$startDate	= I('startDate', date('Y-m-d'));	//开始日期
		$endDate	= I('endDate', date('Y-m-d'));		//结束日期
		$regionLevel= 0;
		
		$map['sales.createTime']= array('between',array(strtotime($startDate), strtotime($endDate) + 86400));
		
		if($storeId){
			$regionLevel = 3;
			$region = D('store')->field("id,name")->where(array('id'=>$storeId))->find();
			
			if($this->user['roleId'] == 7){
				$map['sales.userId'] = $this->user['id'];
			}else{
				$map['sales.storeId'] = $storeId;
			}
		}else{
			$this->ajaxReturn(300, L('error'));
		}
		

		
//		elseif ($microAreaId) {
//			$regionLevel = 2;
//			$region = D('region')->where(array("id"=>$microAreaId))->field("name")->find();
//			$map['r.id'] = $microAreaId;
//		}elseif ($cityId) {
//			$regionLevel = 1;
//			$region = D('region')->where(array("id"=>$cityId))->field("name")->find();
//			$map['c.id'] = $cityId;
//		}
		
		$data  = D(MODULE_NAME)->salesCount($map);

		$this->assign('storeId', $storeId);
		$this->assign('startDate', $startDate);
		$this->assign('endDate', $endDate);
		$this->assign('date', $startDate == $endDate ? $startDate : $startDate.'~'.$endDate);
		$this->assign('regionLevel', $regionLevel);
		$this->assign('regionName', $region['name']);
		$this->assign('data', $data);
		
		$this->display();
	}
	
	
	/**
	 * 销量明细查询
	 */
	public function report(){
		$storeId	= I('storeId');		//营业厅id
		
		$startDate	= I('startDate', date('Y-m-d'));	//开始日期
		$endDate	= I('endDate', date('Y-m-d'));		//结束日期

		$map['sales.createTime']= array('between',array(strtotime($startDate), strtotime($endDate) + 86400));
		
		if($storeId){
			$regionLevel = 3;
			$region = D('store')->field("id,name")->where(array('id'=>$storeId))->find();
			
			if($this->user['roleId'] == 7){
				$map['sales.userId'] = $this->user['id'];
			}else{
				$map['sales.storeId'] = $storeId;
			}
			
			$map['sales.verify'] = 1;
		}else{
			$this->ajaxReturn(300, L('error'));
		}
		
		$list  = D(MODULE_NAME)->report($map);

		$this->assign('storeId', $storeId);
		$this->assign('date', $startDate == $endDate ? $startDate : $startDate.'~'.$endDate);
		$this->assign('regionLevel', $regionLevel);
		$this->assign('regionName', $region['name']);
		$this->assign('list', $list);
		
		$this->display();
	}
	
	/**
	 * 业绩展示
	 */
	public function ranking(){
		$page	= I('page', 1);	// 要显示第几页数据
		$num	= I('num', 20);	// 每页显示多少条数据
		
		$data	= array();
		$res	= D('UserSales')->limit($num)->page($page)->order("monthSales DESC, monthSalesByMain")->select();
		
		if($res){
			foreach ($res as $row){
				$data[] = array(
					'name' => $row['name'],
					'storeName' => $row['storeName'],
					'icon' => '',
					'content' => "月销量{$row['monthSales']}台,月重点销量{$row['monthSalesByMain']}台"
				);
			}
			$this->ajaxReturn(200, L('success'), $data);
		}else{
			$this->ajaxReturn(300,  L('no_more'));
		}
	}
	
		
	/**
	 * 发起冲突申诉
	 */
	public function addDispute(){
		$imei = I('imei');

		$sales = D('Sales')->where(array('imei'=>$imei))->find();
		//找不到销量记录则提示
		if(! $sales){
			$this->ajaxReturn(300, L('can_not_find_this_imei'));
		}
		//如果是自己录的，则提示
		if($sales['userId'] == $this->user['id']){
			$this->ajaxReturn(300, L('imei_is_yours'));
		}
		//如果已发起过，则提示
		$dispute = D('SalesDispute')->where(array('imei'=>$imei, 'createUserId'=>$this->user['id']))->find();
		if($dispute){
			$this->ajaxReturn(300, L('dispute_already_exists'));
		}
		
		$data['imei'] = $imei;
		$data['salesId'] = $sales['id'];
		$data['createUserId'] = $this->user['id'];
		$data['toUserId'] = $sales['userId'];
		$data['createTime'] = time();
		$data['status'] = 0;
		
		if(D('SalesDispute')->add($data)){
			$this->ajaxReturn(200, L('success'));
		}else{
			$this->ajaxReturn(300, L('error'));
		}
		
	}
	
	/**
	 * 冲突申诉
	 */
	public function dispute (){	
		import("ORG.Date");
		$Date = new Date(date('Y-m'));
		
		$startTime = I('startTime', date('Y-m-d', strtotime($Date->firstDayOfMonth())));
		$endTime = I('endTime', date('Y-m-d', strtotime($Date->lastDayOfMonth()) > time() ? strtotime(date('Y-m-d')) : strtotime($Date->lastDayOfMonth())));
		
		$where['d.createTime'][] = array('egt', strtotime($startTime));
		$where['d.createTime'][] = array('elt', strtotime($endTime)+(24*60*60-1));
		
		//如果是市场总监，则查找其管理地市下的销售人员
		if($this->user['roleId'] == 3){
			$where['_string'] = "cc.id = {$this->user['cityId'][0]} OR tc.id={$this->user['cityId'][0]}";
			$where['d.status'] = array('in', '3,4,5');
		}else{
			$where['_string'] = "createUserId = {$this->user['id']} OR toUserId={$this->user['id']}";
		}
		
		$field = array(
            'cu.id'=>'createUserId',
            'cu.realName'=>'createRealName',
            'tu.id'=>'toUserId',
            'tu.realName'=>'toRealName',
            'd.id',
            's.imei',
			'd.createTime',
			'm.name' => 'model',
			'b.name' => 'brand',
			'd.status',
		);
	
		$list = D("SalesDispute")->field($field)->alias("d")
				->join(C('DB_PREFIX')."admin AS cu ON cu.id = d.createUserId")
				->join(C('DB_PREFIX')."store AS cs ON cs.id = cu.storeId")
				->join(C('DB_PREFIX')."region AS cr ON cr.id = cu.regionId")
				->join(C('DB_PREFIX')."region AS cc ON cc.id = cr.pid")
				->join(C('DB_PREFIX')."admin AS tu ON tu.id = d.toUserId")
				->join(C('DB_PREFIX')."store AS ts ON ts.id = tu.storeId")
				->join(C('DB_PREFIX')."region AS tr ON tr.id = tu.regionId")
				->join(C('DB_PREFIX')."region AS tc ON tc.id = tr.pid")
				->join(C('DB_PREFIX')."sales AS s ON s.id = d.salesId")
				->join(C('DB_PREFIX')."model AS m ON m.id = s.modelId")
				->join(C('DB_PREFIX')."brand AS b ON b.id = m.brandId")
				->where($where)
				->select();

		$success = 0;

		foreach ($list as &$n){
			$n['progress'] = D('salesDispute')->getProgress($n['status'], $n['createUserId'], $n['createRealName'], $n['toUserId'], $n['toRealName']);
			if(in_array($n['status'], array(5,6)) && $n['createUserId'] == $this->user['id']){
				$success++;
			}
		}
		$where['d.createTime'][] = array('egt', strtotime($startTime));
		$where['d.createTime'][] = array('elt', strtotime($endTime)+(24*60*60-1));
		
		if(strtotime($startTime) == strtotime($endTime) ){
			$timeLimit = $startTime;
		}else{
			$timeLimit = $startTime .'~'. $endTime;
		}
		
		$this->assign('timeLimit', $timeLimit);
		$this->assign('startTime', $startTime);
		$this->assign('endTime', $endTime);
		$this->assign('success', $success);
		$this->assign('user', $this->user);
		$this->assign('list', $list);
		$this->display();
	}
	
	/**
	 * 冲突记录详情
	 */
	public function disputeDetail(){
		$id = I('id');
		
		$field = array(
            'cu.id'=>'createUserId',
            'cu.realName'=>'createRealName',
            'cs.name'=>'createUserStoreName',
            'cc.id'=>'createUserCityId',
            'tu.id'=>'toUserId',
            'tu.realName'=>'toRealName',
            'ts.name'=>'toUserStoreName',
            'tc.id'=>'toUserCityId',
            'd.id',
            's.imei',
			's.createTime'=>'salesCreateTime',
			'd.createTime'=>'disputeCreateTime',
			'm.name' => 'model',
			'b.name' => 'brand',
			'd.status',
			'u.realName'=>'owner',	//当前IMEI所有者
		);
		$v = D("SalesDispute")->field($field)->alias("d")
			->join(C('DB_PREFIX')."admin AS cu ON cu.id = d.createUserId")
			->join(C('DB_PREFIX')."store AS cs ON cs.id = cu.storeId")
			->join(C('DB_PREFIX')."region AS cr ON cr.id = cu.regionId")
			->join(C('DB_PREFIX')."region AS cc ON cc.id = cr.pid")
			->join(C('DB_PREFIX')."admin AS tu ON tu.id = d.toUserId")
			->join(C('DB_PREFIX')."store AS ts ON ts.id = tu.storeId")
			->join(C('DB_PREFIX')."region AS tr ON tr.id = tu.regionId")
			->join(C('DB_PREFIX')."region AS tc ON tc.id = tr.pid")
			->join(C('DB_PREFIX')."sales AS s ON s.id = d.salesId")
			->join(C('DB_PREFIX')."admin AS u ON u.id = s.userId")
			->join(C('DB_PREFIX')."model AS m ON m.id = s.modelId")
			->join(C('DB_PREFIX')."brand AS b ON b.id = m.brandId")
			->where(array('d.id'=>$id))
			->find();

		// 如果当前记录是对当前登录用户发起的，且状态为0，
		if($v['toUserId'] == $this->user['id'] && $v['status'] == 0){
			$v['status'] = 1;
			
			// 则更改状态为当前登录用户已知晓
			D("SalesDispute")->where(array('id'=>$id))->save(array('status'=>1));
			//记录 imei 申诉记录更改历史
			$history['disputeId'] = $id;
			$history['userId'] = $this->user['id'];
			$history['historyStatus'] = 0;
			$history['newStatus'] = 1;
			$history['time'] = time();
			$history['content'] = '已知晓';
			D("SalesDisputeHistory")->add($history);
		}
		//处理进度
		$v['progress'] = D('salesDispute')->getProgress($v['status'], $v['createUserId'], $v['createRealName'], $v['toUserId'], $v['toRealName']);
		//状态说明
		$v['history'] = D("SalesDisputeHistory")->where(array('disputeId'=>$id, 'newStatus'=>$v['status']))->find();

		$this->assign('user', $this->user);
		$this->assign('v', $v);
		$this->display();
	}
    
    /**
	 * 删除冲突申诉记录 
	 */
	public function deleteDispute(){
		$id = I('id');
		
		if(D('SalesDispute')->where(array('id'=>$id, 'createUserId'=> $this->user['id'], 'status'=>0))->delete()){
			$this->ajaxReturn(200, L('success'), array('id'=>$id));
		}else{
			$this->ajaxReturn(300, L('error'));
		}
		
	}
	
	/**
	 * 设置冲突申诉记录状态
	 */
	public function setDisputeStatus(){
		$id = I('id');
		$historyStatus = I('historyStatus');
		$newStatus  = I('newStatus');
		$content = I('content');
		
		if(empty($content) && in_array($newStatus, array(3,6,7)) == false){
			$this->ajaxReturn(300, '请填写理由', array('status'=>$newStatus));
		}
		
		$res = D('salesDispute')->setStatus($id, $historyStatus, $newStatus, $content);
		
		if($res){
			$this->ajaxReturn(200, L('success'));
		}else{
			$this->ajaxReturn(300, L('error'), array('status'=>$newStatus));
		}
	}
	
}

/* End of file salesAction.class.php */